<?php

class Model_Settings extends ORM {
    protected static $s_table_name = 'settings';
    protected $_table_name = 'settings';
    
    private static $_values;

    private static function decodeValues($valuesStr){
        return unserialize($valuesStr);
    }
    private static function encodeValues($valuesArray){
        return serialize($valuesArray);
    }
    
    public static function reinit(){
        self::getAllSettings();
    }
    public static function init(){
        if(!is_array(self::$_values)){
            self::getAllSettings();
        }
    }
    
    private static function getAllSettings(){
        $settings = new Model_Settings();
        $r = $settings->order_by('datetime', 'desc')->find_all();
        $res = $r->as_array();
        
        foreach($res as &$v){
            $v = $v->as_array();
        }
        unset($v);
        
        if(count($res) < 1){
            self::$_values = array();
        }else{
            $values  = self::decodeValues($res[0]['values']);
            if(!is_array($values)){
                $values = array();
            }
            self::$_values = $values;
        }
//        echo Debug::dump($res);
    }
    
    public static function getVal($key){
        self::init();
        return self::$_values[$key];
    }
    
    public static function getAllVals(){
        self::init();
        return self::$_values;
    }
    
    public static function setVal($key, $value){
        self::$_values[$key] = $value;
    }
    
    public static function saveValues(){
        $values = self::encodeValues(self::$_values);
        $user_id = Auth::getCurrent();
        $user_id = $user_id->id;
        
        $settings = new Model_Settings();
        $settings->values = $values;
        $settings->user_id = $user_id;
        $settings->datetime = Date::nowStr();
        $settings->create();
    }
    
    private static function valFilter(){
        foreach(self::$_values as $k=>$v){
            
        }
    }
    
    
}